// 导航守卫
import router from '@/router'
import store from '@/store'

// 全局前置守卫
router.beforeEach(async(to, from, next) => {
  // 如果去登录页、注册页、404、放行,或者有token放行
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      const username = store.state.user.myuserInfo.username
      if (!username) {
        await store.dispatch('user/userInfo')
        const menus = store.state.user.myuserInfo.menus
        const res = await store.dispatch('permission/filterRoutes', menus)
        router.addRoutes([
          ...res,
          { path: '*', redirect: '/404', hidden: true }
        ])
        next(to.path)
      }
      next()
    }
  } else {
    const pathArray = ['/login', '/register', '/404']
    if (pathArray.indexOf(to.path) !== -1 || token) {
      next()
    } else {
      next('/login')
    }
  }
})
